#include <iostream>
#include <unistd.h>

#include <pthread.h>
#include <sys/types.h>

pthread_rwlock_t rwlock; // 读写锁
static int g_data = 0; // 共享资源]

pthread_mutex_t lockScreen;

void *Reader(void *args)
{
    int id = *(int *)args;

    while (true)
    {
        pthread_rwlock_rdlock(&rwlock); // 读者加锁

        pthread_mutex_lock(&lockScreen);
        std::cout << "读者-" << id << " 正在读取数据, 数据是: " << g_data << std::endl;
        pthread_mutex_unlock(&lockScreen);
        sleep(2);
        pthread_rwlock_unlock(&rwlock); // 读者解锁
        sleep(1);
    }
    delete (int *)args;
    return nullptr;
}

void *Writer(void *args)
{
    int id = *(int *)args;
    while (true)
    {
        pthread_rwlock_wrlock(&rwlock); // 写者加锁
        g_data += 2;                    // 修改共享数据

        pthread_mutex_lock(&lockScreen);
        std::cout << "写者- " << id << " 正在写入. 新的数据是: " << g_data << std::endl;
        pthread_mutex_unlock(&lockScreen);
        sleep(1);
        pthread_rwlock_unlock(&rwlock); // 解锁
        sleep(1);

    }
    delete (int *)args;
    return NULL;
}

int main()
{
    pthread_rwlock_init(&rwlock, nullptr); // 初始化读写锁
    pthread_mutex_init(&lockScreen,nullptr);
    const int reader_num = 5; // 读者数量
    const int writer_num = 10;  // 写者数量
    const int total = reader_num + writer_num;
    pthread_t threads[total];

    for (int i = 0; i < reader_num; i++)
    {
        int *id = new int(i);
        pthread_create(&threads[i], 0, Reader, id);
    }

    for (int i = reader_num; i < total; i++)
    {
        int *id = new int(i - reader_num);
        pthread_create(&threads[i], 0, Writer, id);
    }

    for (int i = 0; i < total; i++)
    {
        pthread_join(threads[i], nullptr);
    }
    return 0;
}